package com.simplehire.controller;

import com.simplehire.service.InterviewService;
import com.simplehire.util.FileContentExtractor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@Slf4j
@RequiredArgsConstructor
public class InterviewController {

    private final InterviewService interviewService;

    /**
     * 显示面试页面（处理GET请求）
     */
    @GetMapping("/interview")
    public String showInterviewPage() {
        // 返回interview.html模板
        return "interview";
    }

    /**
     * 处理简历上传和面试开始（处理POST请求）
     */
    @PostMapping("/interview/process")
    public String processResume(@RequestParam("resume") MultipartFile resume,
                                @RequestParam("jobDescription") String jobDescription,
                                @RequestParam(value = "aiModel", defaultValue = "deepseek") String aiModel,
                                Model model) {
        try {
            // 参数校验
            if (resume.isEmpty()) {
                model.addAttribute("error", "请选择简历文件");
                return "interview";
            }
            if (jobDescription == null || jobDescription.trim().isEmpty()) {
                model.addAttribute("error", "请输入职位描述");
                return "interview";
            }

            log.info("接收简历文件: {}, 选择的AI模型: {}", resume.getOriginalFilename(), aiModel);

            // 提取文件内容
            String resumeText = FileContentExtractor.extractContent(resume);

            // 根据选择的AI模型生成不同的分析结果
            String aiResponse;
            String interviewQuestions;

            switch (aiModel.toLowerCase()) {
                case "tongyi":
                    // 通义千问的处理逻辑
                    aiResponse = "通义千问分析结果：\n" + interviewService.generateInterviewResult(resumeText, aiModel);
                    interviewQuestions = "通义千问生成的面试问题：\n" +
                            interviewService.generateInterviewQuestions(jobDescription, resumeText, aiModel);
                    break;
                case "douban":
                    // 豆包的处理逻辑
                    aiResponse = "豆包分析结果：\n" + interviewService.generateInterviewResult(resumeText, aiModel);
                    interviewQuestions = "豆包生成的面试问题：\n" +
                            interviewService.generateInterviewQuestions(jobDescription, resumeText, aiModel);
                    break;
                case "deepseek":
                default:
                    // DeepSeek的处理逻辑（默认）
                    aiResponse = interviewService.generateInterviewResult(resumeText, aiModel);
                    interviewQuestions = interviewService.generateInterviewQuestions(jobDescription, resumeText, aiModel);
                    break;
            }

            // 将结果传递到结果页面
            model.addAttribute("aiResponse", aiResponse);
            model.addAttribute("interviewQuestions", interviewQuestions);
            model.addAttribute("selectedModel", aiModel); // 传递选择的模型到页面

            return "result";
        } catch (IOException e) {
            log.error("处理简历失败", e);
            model.addAttribute("error", "处理简历失败: " + e.getMessage());
            return "interview";
        } catch (Exception e) {
            log.error("处理请求异常", e);
            model.addAttribute("error", "系统异常: " + e.getMessage());
            return "interview";
        }
    }

    /**
     * 处理AI聊天请求
     */
    @PostMapping("/chat")
    @ResponseBody
    public String chat(
            @RequestParam String question,
            @RequestParam String context,
            @RequestParam(value = "aiModel", defaultValue = "deepseek") String aiModel) {
        try {
            log.info("接收AI聊天请求，问题：{}，模型：{}", question, aiModel);

            // 参数校验
            if (question == null || question.trim().isEmpty()) {
                return "问题不能为空";
            }
            if (context == null) {
                context = ""; // 允许空上下文
            }

            return interviewService.chatWithAI(question, context, aiModel);
        } catch (Exception e) {
            log.error("处理AI聊天请求失败", e);
            return "处理请求时发生错误：" + e.getMessage();
        }
    }
}